import React, { useState, useEffect, useRef } from "react";
import { Graph, register, treeToGraphData } from "@antv/g6";
import { ReactNode } from "@antv/g6-extension-react";
import { Renderer as SVGRenderer } from "@antv/g-svg";
import {
  Button,
  Modal,
  Card,
  Typography,
  Tag,
  Badge,
  Input,
  Space,
  Alert,
  Tooltip,
  message,
} from "antd";
import {
  EditOutlined,
  LinkOutlined,
  PlusOutlined,
  MinusOutlined,
  SmileTwoTone,
  HeartTwoTone,
  CheckCircleTwoTone,
} from "@ant-design/icons";

import { createRoot } from "react-dom/client";
import { set } from "lodash";

const { Title, Text } = Typography;

// 注册React节点扩展
register("node", "react", ReactNode);

const NodeComponent = ({ data, onChange, graph }) => {
  const [modalVisible, setModalVisible] = useState(false);
  const [editValue, setEditValue] = useState(data.url || "");
  console.log(data, "data");
  const [fold, setFold] = useState(true);
  // 显示详细信息模态框
  const showDetails = () => {
    setModalVisible(true);
  };

  // 保存编辑后的URL
  const handleSave = () => {
    onChange?.({ ...data, url: editValue });
    setModalVisible(false);
  };

  return (
    <Card
      size="small"
      bordered
      style={{
        width: 280,
        borderRadius: 8,
        position: "relative",
        boxShadow: "0 2px 8px rgba(0,0,0,0.1)",
        borderColor: data.status === "error" ? "#ff4d4f" : "#d9d9d9",
      }}
      title={
        <Space>
          <Text strong>{data.id}</Text>
          <Tag color={data.type === "local" ? "blue" : "purple"}>
            数据状态展示
          </Tag>
        </Space>
      }
      extra={<Badge status={data.status} />}
      // onClick={(e) => {
      //   e.stopPropagation();
      //   message.success("点击了节点");
      //   console.log("data");
      // }}
    >
      {/* 展开收起功能 */}
      <div
        style={{
          position: "absolute",
          right: -15,
          top: 35,
          backgroundColor: "#e3e5e9",
          borderRadius: "50%",
        }}
      >
        {data.children && data.children.length > 0 && (
          <>
            {fold ? (
              <Button
                type="text"
                icon={<MinusOutlined />}
                onClick={() => {
                  setFold(false);
                  graph.collapseElement(data.id);
                }}
              />
            ) : (
              <Button
                type="text"
                icon={<PlusOutlined />}
                onClick={() => {
                  setFold(true);
                  graph.expandElement(data.id);
                }}
              />
            )}
          </>
        )}
      </div>
      <Space direction="vertical" style={{ width: "100%" }}>
        <Space>
          <Space>
            <SmileTwoTone />
            <HeartTwoTone twoToneColor="#eb2f96" />
            <Tooltip title="成功">
              <CheckCircleTwoTone twoToneColor="#52c41a" />
            </Tooltip>
          </Space>
          <a href="">事件</a>
          <a href="">监控</a>
        </Space>
      </Space>
    </Card>
  );
};

const CustomNodeGraph = () => {
  const containerRef = useRef();
  const graphRef = useRef();
  // 树形数据结构
  const [treeData, setTreeData] = useState({
    id: "root",
    name: "Root Server",
    status: "success",
    type: "local",
    url: "http://localhost:3000",
    children: [
      {
        id: "server1",
        name: "Server 1",
        status: "success",
        type: "local",
        url: "http://server1.local",
        children: [
          {
            id: "server1-1",
            name: "Server 1-1",
            status: "success",
            type: "local",
            url: "http://server1-1.local",
          },
          {
            id: "server1-2",
            name: "Server 1-2",
            status: "error",
            type: "remote",
            url: "http://server1-2.local",
          },
        ],
      },
      {
        id: "server2",
        name: "Server 2",
        status: "warning",
        type: "remote",
        url: "http://server2.local",
        children: [
          {
            id: "server2-1",
            name: "Server 2-1",
            status: "warning",
            type: "remote",
            url: "http://server2-1.local",
          },
          {
            id: "server2-2",
            name: "Server 2-2",
            status: "success",
            type: "local",
            url: "http://server2-2.local",
          },
        ],
      },
    ],
  });
  // 给节点添加collapsed属性，用于控制是否折叠
  // const addCollapsedToNodes = (node) => {
  //   if (node.children && node?.children?.length > 0) {
  //     node.collapsed = true;
  //     node?.children?.forEach((item) => addCollapsedToNodes(item));
  //   } else {
  //     node.collapsed = false;
  //   }
  // };

  // 初始化图
  useEffect(() => {
    if (!containerRef.current) return;

    const { nodes, edges } = treeToGraphData(treeData, {
      getNodeData: (datum, depth) => {
        if (!datum.style) datum.style = {};
        datum.style.collapsed = depth >= 2;
        if (!datum.children) return datum;
        const { children, ...restDatum } = datum;
        return { ...restDatum, children: children.map((child) => child.id) };
      },
    });

    console.log(nodes, edges, "nodes");

    // 添加额外边
    // edges?.push(
    //   {
    //     source: "server2",
    //     target: "server1-2",
    //   },
    //   {
    //     source: "server1",
    //     target: "server2-2",
    //   }
    // );
    const graph = new Graph({
      container: containerRef.current,

      // data:{nodes,edges},
      data: {
        nodes: [
          {
            id: "root",
            name: "Root Server",
            status: "success",
            type: "local",
            url: "http://localhost:3000",
            style: {
              collapsed: false,
            },
            children: ["server1", "server2"],
          },
          {
            id: "server1",
            name: "Server 1",
            status: "success",
            type: "local",
            url: "http://server1.local",
            style: {
              collapsed: false,
            },
            children: ["server1-1", "server1-2"],
          },
          {
            id: "server1-1",
            name: "Server 1-1",
            status: "success",
            type: "local",
            url: "http://server1-1.local",
            style: {
              collapsed: true,
            },
          },
          {
            id: "server1-2",
            name: "Server 1-2",
            status: "error",
            type: "remote",
            url: "http://server1-2.local",
            style: {
              collapsed: true,
            },
          },
          {
            id: "server2",
            name: "Server 2",
            status: "warning",
            type: "remote",
            url: "http://server2.local",
            style: {
              collapsed: false,
            },
            children: ["server2-1", "server2-2"],
          },
          {
            id: "server2-1",
            name: "Server 2-1",
            status: "warning",
            type: "remote",
            url: "http://server2-1.local",
            style: {
              collapsed: true,
            },
          },
          {
            id: "server2-2",
            name: "Server 2-2",
            status: "success",
            type: "local",
            url: "http://server2-2.local",
            style: {
              collapsed: true,
            },
          },
        ],
        edges: [
          {
            source: "root",
            target: "server1",
          },
          {
            source: "root",
            target: "server2",
          },
          {
            source: "server1",
            target: "server1-1",
          },
          {
            source: "server1",
            target: "server1-2",
          },
          {
            source: "server2",
            target: "server1-2",
          },
          {
            source: "server1",
            target: "server2-2",
          },
          {
            source: "server2",
            target: "server2-1",
          },
          {
            source: "server2",
            target: "server2-2",
          },
        ],
      },
      autoFit: "center",
      node: {
        type: "react",
        style: {
          component: (data) => {
            return (
              <NodeComponent
                data={data}
                graph={graph}
                onChange={(newData) => {
                  graph.updateData("node", {
                    id: data.id,
                    data: newData,
                  });
                }}
              />
            );
          },
          size: [288, 60],
          ports: [{ placement: "left" }, { placement: "right" }],
          radius: 4,
        },
      },
      edge: {
        type: "cubic-horizontal",
        style: {
          // labelText: (d) => d.id,
          // labelBackground: true,
          endArrow: true,
          stroke: "#a0a0a0",
          lineWidth: 2,
        },
      },

      layout: {
        type: "compact-box",
        direction: "LR",
        getHeight: function getHeight() {
          return 0;
        },
        getWidth: function getWidth() {
          return 120;
        },
        getVGap: function getVGap() {
          return 50;
        },
        getHGap: function getHGap() {
          return 100;
        },
      },
      behaviors: ["drag-canvas", "zoom-canvas", "drag-node", "drag-element"],
    });
    // graph.setLayout({
    //   type: "force",
    //   preventOverlap: true, // 防止节点重叠
    //   nodeStrength: -50, // 节点间斥力，负值为斥力
    //   edgeStrength: 0.5, // 边的强度，会影响边的长度
    // });
    // graphRef.current = graph;
    graph.render();
    // graph.layout();

    return () => graph.destroy();
  }, []);

  return (
    <div style={{ display: "flex", flexDirection: "column", height: "100vh" }}>
      <div
        ref={containerRef}
        style={{
          flex: 1,
          background: "#f0f2f5",
          margin: 16,
          borderRadius: 8,
          overflow: "hidden",
          boxShadow: "0 2px 8px rgba(0,0,0,0.1)",
        }}
      />
    </div>
  );
};

export default CustomNodeGraph;
